package com.xmxsuperstar.app.gg;

import java.util.concurrent.CountDownLatch;

public class MoniterThread implements Runnable {
	
	private static final int PROGRESS_LENGTH = 51;

	private CountDownLatch latch;

	public MoniterThread(CountDownLatch latch) {
		this.latch = latch;
	}

	@Override
	public void run() {
		Statics statics = Statics.getInstance();
		int percent = 0;
		
		long lastCompleted=0;
		long currentCompleted=0;
		
		long currentTime=System.currentTimeMillis();
		long lastTime=System.currentTimeMillis();

		do {
			currentTime=System.currentTimeMillis();
			currentCompleted = statics.getCompleted();
			
			percent = (int) (currentCompleted * 100 / statics
					.getFileLength());

			int c = percent * PROGRESS_LENGTH / 100;
			
			StringBuilder sb = new StringBuilder(80);
			
			sb.append('[');
			for (int j = 1; j <= c; j++) {
				sb.append('-');
			}
			for (int j = c + 1; j <= PROGRESS_LENGTH; j++) {
				sb.append(' ');
			}
			sb.append(']');
			sb.append(String.format("%1$3s", percent));
			sb.append("% ");
			sb.append(Utils.calRate(currentCompleted, lastCompleted, currentTime, lastTime));
			sb.append(" ").append(Utils.calETA(currentCompleted, lastCompleted, currentTime, lastTime));
			
			System.out.print(sb);
			
			lastTime = currentTime;
			lastCompleted = currentCompleted;
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			if (percent < 100 && System.console() != null) {
				for (int j = 1; j <= sb.length(); j++) {
					System.out.print('\b');
				}
			} else {
				System.out.println();
			}
		} while (percent < 100);
		
		latch.countDown();
	}

}
